//剑指 Offer 58 - I. 翻转单词顺序
//输入一个英文句子，翻转句子中单词的顺序，但单词内字符的顺序不变。为简单起见，标点符号和普通字母一样处理。例如输入字符串"I am a student. "，则输出"student. a am I"。
//
//https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/description/?favorite=xb9nqhhg&orderBy=most_votes&languageTags=c

char* reverseWords(char* s)
{
    int len = strlen(s);
    int left = len - 1;
    //从后找到第一个不为空格的元素

    int right = len - 1;
    char* ret = (char*)malloc(sizeof(char) * (len + 1));
    int index = 0;
    int cur = 0;
    while (left >= 0)
    {
        if (*(left + s) == ' ')
        {
            left--;
        }
        else
        {
            right = left;
            while (*(left + s) != ' ' && left >= 0)
            {
                left--;
            }
            cur = left + 1;
            while (cur <= right)
            {
                *(ret + index) = *(s + cur);
                index++;
                cur++;
            }
            *(ret + index) = ' ';
            index++;
        }

    }
    if (index >= 1 )
    {
        *(ret + index - 1) = '\0';
    }
    else
    {
        ret = "";
    }
    return ret;
}